<template>
  <div class="container-recommend animate__animated animate__zoomIn">
    <div class="category-list">
      <button :class="['category-list-item', productTypeStore.selectedTypeId === '' ? 'active-btn' : '']"
        @click="selectCategory('')">全部</button>
      <button :class="['category-list-item', productTypeStore.selectedTypeId === type.id ? 'active-btn' : '']"
        @click="selectCategory(type.id)" v-for="type in productTypeStore.typeList.slice(1)" :key="type.id">
        {{ type.typeName }}
      </button>
    </div>
    <div class="waterfall-container" v-infinite-scroll="loadMore" :infinite-scroll-disabled="disabled"
      :infinite-scroll-distance="10" :infinite-scroll-immediate="false" :infinite-scroll-delay="500">
      <Waterfall :list="productStore.productList" imgSelector="image" :width="220" :animationEffect="'animate__zoomIn'"
        :animationDelay="200" :animationDuration="1000" :posDuration="800">
        <template #default="{ item, url }">
          <div class="waterfull-card" @click="(e) => showDetail(item.id, e)">
            <!-- 封面 -->
            <LazyImg :url="Array.isArray(url) ? url[0] : url" style="border-radius: 10px;" />

            <div class="footer">
              <!-- 标题 -->
              <div class="title"><span>{{ item.title }}</span></div>
              <!-- 价格和发货方式 -->
              <div class="price">
                <div style="display: flex; gap: 5px;align-items: baseline;">
                  <span style="color: #FF3C55; font-weight: 600; font-size: 14px;">￥{{ formatPrice(item.price) }}</span>
                  <span style="font-size: 10px; color: #666666; text-decoration: line-through;">
                    ￥{{ formatPrice(item.originalPrice) }}
                  </span>
                </div>
                <span style="font-size: 12px;color: #666666;">{{ item.postType === 0 ? '邮寄' : '自提' }}</span>
              </div>
              <!-- 头像和想要人数 -->
              <div class="avatar-Like">
                <div class="avatar">
                  <img class="avatar-img"
                    :src="item.avatar || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'"
                    style="width: 25px; border-radius: 50%; outline: none;">
                  <span style="margin-left: 5px; color: #666666; font-size: 12px;">{{ item.nickName }}</span>
                </div>
                <div class="like">
                  <span>
                    <svg class="icon" aria-hidden="true">
                      <use xlink:href="#icon-shoucang"></use>
                    </svg>
                  </span>
                  <span style="font-size: 12px; color: #666666;">{{ item.likeCount > 999 ? "999+" : item.likeCount
                    }}</span>
                </div>
              </div>
            </div>
          </div>
        </template>
      </Waterfall>
      <!-- 加载状态提示 -->
      <div class="loading-status" v-if="productStore.productList.length > 0">
        <el-text v-if="!productStore.hasMore" type="info">没有更多了</el-text>
        <el-text v-else-if="loading" type="info">加载中...</el-text>
      </div>
    </div>
  </div>
  <!-- 商品详情卡片 -->
  <productInfoDetail ref="detail" />
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { LazyImg, Waterfall } from 'vue-waterfall-plugin-next'
import productInfoDetail from '@/components/productDetail/ProductInfoDetail.vue'
import 'vue-waterfall-plugin-next/dist/style.css'
import { useProductStore, useProductTypeStore, useProductDetailStore } from '@/stores'
import { formatPrice } from '@/utils/formatDate'

// 获取 store 实例
const productStore = useProductStore()
const productTypeStore = useProductTypeStore()
// 详情组件
const detail = ref()
// 加载状态
const loading = ref(false)

// 计算是否禁用无限滚动
const disabled = computed(() => loading.value || !productStore.hasMore)

// 在 onMounted 中检查并加载数据
onMounted(() => {
  // 如果store中没有数据，就加载数据
  if (productTypeStore.typeList.length === 0) {
    getAllTypes()
  }
  if (productStore.productList.length === 0) {
    getProductList()
  }
})

// 点击商品卡片，显示商品详情
const showDetail = async (productId: string, event: MouseEvent) => {
  const card = event.currentTarget as HTMLElement
  const rect = card.getBoundingClientRect()
  // 先获取商品详情
  useProductDetailStore().getProductDetail(productId)
  // 然后显示详情页，传递卡片位置信息
  detail.value.show({
    x: rect.left,
    y: rect.top,
    width: rect.width,
    height: rect.height
  })
}

// 触底加载更多
const loadMore = async () => {
  if (loading.value || !productStore.hasMore) return
  loading.value = true
  try {
    await getProductList()
  } finally {
    loading.value = false
  }
}

// 选择类别并获取商品列表
const selectCategory = (typeId: string) => {
  // 选择类别
  productTypeStore.selectedTypeId = typeId
  // 清空旧数据，重新按照类别加载新数据
  getProductList(true, typeId)
}

// 商品的类别相关数据和逻辑
import useCategoryList from '@/hooks/useCategoryList'
const { getAllTypes } = useCategoryList()

// 商品操作相关的数据和逻辑
import useProduct from '@/hooks/useProduct'
const { getProductList } = useProduct()
</script>

<style lang="scss" scoped>
.animate__animated {
  animation-duration: .5s;
}

.container-recommend {
  width: 100%;

  .category-list {
    height: 70px;
    padding-top: 10px;
    display: flex;
    align-items: center;
    position: sticky;
    top: 0%;
    z-index: 10;
    background-color: #ffffff;

    .category-list-item {
      width: 70px;
      height: 40px;
      border: none;
      color: var(--font-color);
      background-color: #ffffff;
      font-size: 16px;
      font-weight: 600;
      border-radius: 20px;
      list-style: none;
      cursor: pointer;

      &:not(.active-btn):hover {
        background-color: var(--dark-background-color);
      }
    }

    .active-btn {
      background: rgba(var(--theme-color-rgb), 0.1);
      color: var(--theme-color);
    }
  }

  .waterfall-container {
    min-height: calc(100vh - 70px);
    padding-bottom: 20px;
  }

  .loading-status {
    text-align: center;
    padding: 10px 0;
  }

  .waterfull-card {
    transition: all .4s;

    &:hover {
      cursor: pointer;
      transform: translateY(-10px);
    }

    .footer {
      padding: 10px 0;

      .title {
        font-size: 14px;
        margin-bottom: 5px;
        font-weight: 600;
        display: block;
        padding-left: 3px;
      }

      .price {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .avatar-Like {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 5px;

        .avatar {
          display: flex;
          align-items: center;
        }

        .like {
          display: flex;
          align-items: center;

          .icon {
            width: 1em;
            height: 1em;
            fill: currentColor;
            overflow: hidden;
          }
        }
      }
    }
  }
}
</style>
